<template>
<div>
  <div>
    <el-input style="width: 200px" placeholder="文档标题(选填)" v-model="titleSearch"></el-input>
    <el-input style="width: 200px; margin: 0 5px" placeholder="文档内容关键字(选填)" v-model="contentSearch"></el-input>
    <el-button type="primary" @click="load(1)">查询</el-button>
    <el-button type="primary" @click="reset">重置</el-button>
  </div>
  <div style="margin: 10px 0">
    <el-button type="primary" plain @click="handleAddOrEdit">新增</el-button>
    <el-button type="danger" plain @click="handleDelBatch">批量删除</el-button>
  </div>
<!--  整个表格，有多选框 -->
  <el-table v-loading="loading" element-loading-text="拼命加载中" :data="tableData" stripe :header-cell-style="{backgroundColor: 'aliceblue',color: '#666'}"
  @selection-change="handleSelectionChange">
<!--    复选框-->
    <el-table-column type="selection" width="55" align="center"></el-table-column>
    <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
<!--    <el-table-column prop="username" label="创建人账号"></el-table-column>-->
    <el-table-column prop="title" label="标题"></el-table-column>
    <el-table-column prop="description" label="简介"></el-table-column>
    <!--show-overflow-tooltip表格内容很多时固定大小 -->
<!--    <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>-->
    <el-table-column prop="content" label="内容" width="90px">
      <template v-slot="scope">
        <el-button @click="previewContent(scope.row.content)" size="mini">预览内容</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="content" label="详情" width="90px">
      <template v-slot="scope">
        <el-button @click="detailContent(scope.row)" size="mini">查看详情</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="authorName" label="发布人" width="80"></el-table-column>
    <el-table-column prop="creatTime" label="创建时间" width="140"></el-table-column>
    <el-table-column prop="modifierName" label="修改人" width="80"></el-table-column>
    <el-table-column prop="updateTime" label="修改时间" width="140"></el-table-column>
    <el-table-column prop="remark" label="备注"></el-table-column>
    <el-table-column fixed="right" label="操作" align="center" width="180px">
      <template v-slot="scope">
        <el-button size="mini" type="primary" plain @click="handleAddOrEdit(scope.row)">编辑</el-button>
        <el-button size="mini" type="danger" plain @click="handleDel(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div style="margin: 10px 0;text-align: center">
    <el-pagination @current-change="handleCurrentChange"
                   :current-page="pageNum"
                   :page-size="pageSize"
                   layout="total,prev,pager,next"
                   :total="total">
    </el-pagination>
  </div>

  <!-- 新增表单需要弹窗包裹 / close-on-click-model点击弹窗外不会关闭-->
  <el-dialog title="文档信息"
             :visible.sync="formVisible"
             width="70%"
             @close="closeDialog"
             :close-on-click-model="false">
    <el-form :model="form"
             label-width="80px"
             style="padding-right: 20px"
             :rules="rules"
             ref="formRef">

      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="标题"></el-input>
      </el-form-item>

      <el-form-item label="简介" prop="description">
        <el-input v-model="form.description" placeholder="简介"></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
<!--        <el-input type="textarea" v-model="form.content" placeholder="内容"></el-input>-->
        <div id="editor"></div>
      </el-form-item>

<!--      <el-form-item label="作者" prop="author">-->
<!--        <el-input v-model="form.author" placeholder="作者"></el-input>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="创建时间" prop="datetime">-->
<!--        <el-input v-model="form.creatTime" placeholder="创建时间"></el-input>-->
<!--      </el-form-item>-->

<!--      <el-form-item label="更新时间" prop="datetime">-->
<!--        <el-input v-model="form.updateTime" placeholder="更新时间"></el-input>-->
<!--      </el-form-item>-->

      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" placeholder="备注"></el-input>
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="formVisible = false">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>

<!-- 预览内容弹窗 -->
  <el-dialog title="预览内容" :visible.sync="contentVisible" width="70%">
    <!-- 显示表格的样式w-e-text   -->
<!--    <div class="w-e-text">-->
<!--    el-card 以卡片形式显示更直观-->
    <el-card class="w-e-text">
      <!--  预览内容主体    -->
      <div v-html="content"></div>
    </el-card>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="contentVisible = false">关闭预览</el-button>
    </div>
  </el-dialog>


</div>
</template>

<script>
import E from 'wangeditor'
import hljs from 'highlight.js'

export default {
  name: "Doc",
  data(){
    return {
      tableData: []//表数据
      ,pageNum: 1//当前页码
      ,pageSize: 15//每页数量
      ,titleSearch: '' //搜索标题
      ,contentSearch: ''//搜索内容
      ,content: ''
      ,total: 0 //数据总条数
      ,formVisible: false //默认不显示新增表单弹窗
      ,form: {}
      ,user: JSON.parse(localStorage.getItem('userInfo') || '{}')
      ,rules: {
        title: [
          {required: true,message: '输入标题',trigger: 'blur'}
        ]
      }
      ,ids: []
      ,editor: null
      ,contentVisible: false //预览内容弹窗
      ,editorFileUpload: this.$apiUrl+'/file/editor/upload'
      ,isEditMode: false //编辑模式
      ,loading: true,
    }
  },
  created() {
    this.load();
  },
  methods: {
    reset(){
      this.titleSearch = ''
      this.contentSearch = ''
      this.load()
    },
    load(pageNum){
      if (pageNum) this.pageNum = pageNum;  //分页查询时自动切换到第一页
      this.$request.get('/doc/findByPage',{
        params:{
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          title: this.titleSearch,
          content: this.contentSearch
        }
      }).then(res => {
        if(res.code === "200"){
          if (res.data){
            if (res.data.records){
              this.tableData = res.data.records
            }
            this.total = res.data.total
          }else {
            this.$message.error("分页数据可能为空")
          }
        }else {
          this.$message.error("获取分页数据失败："+res.msg)
        }
        // if (res.data){
        //   // if (res.data.records){
        //   //   // this.tableData = res.data
        //   //   this.tableData = res.data.records  //若records不显示可替换为List
        //   // }else{
        //   //   alert("res.data.records不存在")
        //   // }
        //   this.total = res.data.total
        // }else {
        //   alert("res.data")
        // }
        this.loading = false
      })
    },
    //切换页码
    handleCurrentChange(pageNum){
      // this.pageNum = pageNum //方法传递过来参数就不用赋值了
      this.load(pageNum)
    },
    //新增弹窗事件||编辑弹窗
    //注意：row无论在哪种模式，永远不为空，只是值内容多少的区别，所以同函数无法精确区分两种模式，要么分函数，要么根据内容来区分
    handleAddOrEdit(row){
      // this.form = row.id ?  JSON.parse(JSON.stringify(row)) : {}

      //判断是否编辑模式，默认false
      if (row.id){
        this.isEditMode = true;
        this.form = JSON.parse(JSON.stringify(row)) //弹窗带出来信息,浅拷贝是内存指向，深拷贝是开区域赋值
      }else {
        this.isEditMode = false; //其实不用写，默认就是false
        this.form = {} //新增数据时清空表单
      }

      this.formVisible = true //显示弹窗
      //弹窗对象是后出现，直接使用会找不到内容div的id,所以设置时钟，等内容div元素创建好之后再去执行
      this.$nextTick(() => {
        //新建富文本对象,#editor是内容div的id
        this.editor = new E(`#editor`)
        //代码高亮插件
        this.editor.highlight = hljs

        //图片上传服务器接口
        // this.editor.config.uploadImgServer = '/file/editor/upload'  //默认前缀是前端服务地址
        this.editor.config.uploadImgServer = this.editorFileUpload
        //file与接口参数名一致
        this.editor.config.uploadFileName = 'file'
        //传令牌鉴权，放在Img头里
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        //传参type，可从url，也可从参数函数传
        this.editor.config.uploadImgParams = {
          // token: xxx
          type: "img"
        }

        // 配置上传成功后的自定义插入逻辑（解决src非字符串问题）
        this.editor.config.uploadImgHooks = {
          customInsert: (insertImg, result, editor) => {
            console.log(result);
            if (result.errno === 0 && result.data?.length > 0) {
              // 根据实际返回结构调整：data是数组，取第一个元素的url对象中的fileUrl
              const imgUrl = result.data[0].url.fileUrl?.trim(); // 去除可能的前后空格
              if (typeof imgUrl === 'string') {
                insertImg(imgUrl);
              } else {
                this.$message.error('图片URL格式不正确');
              }
            } else {
              this.$message.error('图片上传失败：' + (result.msg || '无有效数据'));
            }
          }
        }

        //上传视频
        this.editor.config.uploadVideoServer = this.editorFileUpload
        this.editor.config.uploadVideoName = 'file'
        this.editor.config.uploadVideoHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadVideoParams = {
          type: "video"
        }
        //正式创建
        this.editor.create()
        if (this.isEditMode){
          //创建完成后，在编辑模式下应该赋值
          this.editor.txt.html(row.content)
        }
      })
    },
    //新增保存
    save(){
      //校验表单
      this.$refs.formRef.validate((valid) => {
        if (valid){
          //获取富文本编辑框内容
          this.form.content = this.editor.txt.html()
          //发送请求
          this.$request({
            //有id就是编辑
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form,
            url: this.form.id ? '/doc/update' : '/doc/save'
          }).then(res => {
            if (res.code === '200'){
              //保存成功
              this.$message.success('保存成功')
              this.formVisible = false;
              this.load(this.pageNum)
            }else {
              this.$message.error(res.msg) //错误信息
            }
          })
        }
      })
    },
    //单个删除
    handleDel(row){
      this.$confirm('确认删除《'+row.title+'》文档吗？','确认删除',{type: "warning"}).then(ok => {
        this.$request.delete('/doc/delete/'+row.id).then(res => {
          if (res.code == '200'){
            this.$message.success("删除成功")
          }else {
            this.$message.error("删除失败："+res.msg)
          }
          this.load(this.pageNum) //刷新表格
        })
      }).catch(() => {}) //catch捕捉先不做处理
    },
    //批量删除之前--多选框，参数是选中的行对象
    handleSelectionChange(rows){
      this.ids = rows.map(row => row.id) //流和表达式，将行id提取出来存入数组
    },
    //批量删除
    handleDelBatch(){
      //校验：点击批量删除按钮之前，未选择多选框时提示
      if (!this.ids.length){
        this.$message.warning('请选择需要批量删除的文档！')
        return
      }

      this.$confirm('你确认批量删除['+this.ids+']这些文档吗？','确认删除',{type: "warning"}).then(ok => {
        this.$request.delete('/doc/deleteBatch',{data: this.ids}).then(res => {
          if (res.code == '200'){
            this.$message.success("批量删除成功")
          }else {
            this.$message.error("批量删除失败:"+res.msg)
          }
          this.load(this.pageNum) //刷新表格
        })
      }).catch(() => {}) //catch捕捉先不做处理
    },
    //关闭弹窗后的回调方法
    closeDialog(){
      //清除rules提示信息
      this.$refs.formRef.clearValidate()
      //销毁富文本编辑器对象
      this.editor.destroy()
      this.editor = null
    },
    //预览内容
    previewContent(content){
      if (content){
        this.content = content
        this.contentVisible = true;
      }else {
        this.$message.warning("没有内容可供预览")
      }
    },
    //查看详情
    detailContent(row){
      if (row.content){
        this.$router.push('/docDetail?id='+row.id)
      }else {
        this.$message.warning("此文档没有内容")
      }
    }
  }
}
</script>

<style scoped>
</style>